package com.example.netty.fixlength.client;

import com.example.netty.common.client.ClientHeartBeatServerHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.FixedLengthFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.timeout.IdleStateHandler;

import java.util.concurrent.TimeUnit;

/**
 * <p></p>
 *
 * @author xin
 * @version 2023/11/2 16:06
 **/
@SuppressWarnings("all")
public class FixLengthClientInitializer extends ChannelInitializer<SocketChannel> {
    private static final String DECODER = "decoder";
    private static final String ENCODER = "encoder";
    private static final String PING = "ping";

    /**
     * 为读超时时间（即多长时间没有接受到客户端发送数据）
     */
    private final long readerIdleTime = 0;
    /**
     * 为写超时时间（即多长时间没有向客户端发送数据）
     */
    private final long writerIdleTime = 0;
    /**
     * 所有类型（读或写）的超时时间
     */
    private final long allIdleTime = 0;

    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        ch.pipeline().addLast(new ClientHeartBeatServerHandler())
                .addLast(new IdleStateHandler(readerIdleTime, writerIdleTime, allIdleTime, TimeUnit.SECONDS))
                // 固定 长度， 每一包消息长度必须是 37 字节，只有达到 37 时才会被接收
//                所有的消息，必须是 37 的倍数，不然会截断产生乱码
//                FixLengthServerHandler channelRead 给客户端发送消息
                .addLast(new FixedLengthFrameDecoder(37))
                .addLast(ENCODER, new StringEncoder())
                .addLast(DECODER, new StringDecoder())
                .addLast(new FixLengthClientHandler())
        ;
    }
}
